<template>
  <div class="search-suggestion-container">
    <van-cell
    icon="search"
    v-for="(item,index) in suggestList"
    :key="index"
    @click="onSendClickStr(item)"
    >
    <template #title>
        <div v-html="highlight(item)"></div>
    </template>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from 'network/search'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  created () {
    console.log(this._)
  },
  props: {
    searchContent: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestList: [],
      a: '2'
    }
  },
  methods: {
    // 对联想的字符串进行处理,高亮搜索的字符串
    highlight (str) {
      return str.replaceAll(this.searchContent, `<span style='color:pink;'>${this.searchContent}</span>`)
    },
    // 点击哪一个联想,说明用户要查这个的相关内容
    onSendClickStr (str) {
      console.log('2')
      this.$emit('suggest-search', str)
    }
  },
  watch: {
    // 搜索内容变了,重新发请求,获取最新联想词
    searchContent: {
      handler: debounce(async function (newVal) {
        const { data: res } = await getSearchSuggestion(newVal)
        this.suggestList = res.data.options
      }, 500),
      immediate: true
    }
  }
}
</script>

<style lang='less' scoped>

</style>
